﻿using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
namespace Game02 {
    public class LightMapLoader: MonoBehaviour {
        public ScriptableObject lightingData;
        public Texture2D[] lightmapDirArr;
        public Texture2D[] lightmapColorArr;
        public LightmapRendererInfo[] lightMapInfoArr;

        void Awake() {
            var arr = gameObject.GetComponentsInChildren<Transform>(true);
            for(int i = 0; i < arr.Length; i++) {
                arr[i].gameObject.isStatic = true;
            }
            var lightmapDataArr = new LightmapData[lightmapDirArr.Length];
            for(int i = 0; i < lightmapDataArr.Length; i++) {
                lightmapDataArr[i] = new LightmapData();
                lightmapDataArr[i].lightmapDir = lightmapDirArr[i];
                lightmapDataArr[i].lightmapColor = lightmapColorArr[i];
            }
            ApplyRendererInfo(lightMapInfoArr);
            LightmapSettings.lightmaps = lightmapDataArr;
        }

        void Start() {
        }

        static void ApplyRendererInfo(LightmapRendererInfo[] infos) {
            for(int i = 0; i < infos.Length; i++) {
                var info = infos[i];
                if(info.renderer != null) {
                    info.renderer.lightmapIndex = info.lightmapIndex;
                    info.renderer.lightmapScaleOffset = info.lightmapOffsetScale;
//                    if(info.renderer is MeshRenderer mesh) {
//                        mesh.scaleInLightmap = 0.5f;
//                    }

                    if(info.terrain != null) {
                        info.terrain.lightmapIndex = info.lightmapIndex;
                        info.terrain.lightmapScaleOffset = info.lightmapOffsetScale;
                    }
                }
            }
        }

        public void Set(string folderName) {
            folderName = folderName.Trim();
            if(folderName.Length <= 0)
                return;
            //
            string path = Application.streamingAssetsPath + "/" + folderName + "/LightMaps/" + (Application.platform == RuntimePlatform.WebGLPlayer? "WebGL/": "Window/");
            //
            LightmapData lightmapData = new LightmapData();
            //
            string loadLightPath = path + "lightmap-0_comp_light";
            StartCoroutine(GetAssetBundle(loadLightPath, (abLit)=>{
                if(abLit) {
                    lightmapData.lightmapColor = abLit.LoadAsset<Texture2D>("Lightmap-0_comp_light.exr");
                    abLit.Unload(false);

                    string loadDirPath = path + "lightmap-0_comp_dir";
                    StartCoroutine(GetAssetBundle(loadDirPath, (abDir)=>{
                        if(abDir) {
                            lightmapData.lightmapDir = abDir.LoadAsset<Texture2D>("Lightmap-0_comp_dir.png");
                            abDir.Unload(false);
                            LightmapSettings.lightmaps = new LightmapData[1] { lightmapData };
                        }
                    }));
                }
            }));
        }

        IEnumerator GetAssetBundle(string path, UnityAction<AssetBundle> onGetAssetBundle) {
            using(UnityWebRequest webRequest = UnityWebRequestAssetBundle.GetAssetBundle(path)) {
                yield return webRequest.SendWebRequest();
                if(webRequest.result == UnityWebRequest.Result.Success) {
                    AssetBundle ab = (webRequest.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
                    onGetAssetBundle?.Invoke(ab);
                } else {
                    Debug.Log("error = " + webRequest.error + "\n Load Path = " + path);
                    onGetAssetBundle?.Invoke(null);
                }
            }
        }
    }

    [Serializable]
    public struct LightmapRendererInfo {
        public Terrain terrain;
        public Renderer renderer;
        public int lightmapIndex;
        public Vector4 lightmapOffsetScale;
    }
}
